package com.cloudlinkscm.loms.services.base.notify.dao;

import com.cloudlinkscm.loms.services.base.notify.constant.SendStatusEnum;
import com.cloudlinkscm.loms.services.base.notify.mapper.EmailMessageMapper;
import com.cloudlinkscm.loms.services.base.notify.model.entity.EmailMessage;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author : tac
 * @date : 2017/6/16
 */

@Repository
public class EmailMessageDao extends AbstractMessageDao<EmailMessage> {
    @Autowired
    public EmailMessageDao(EmailMessageMapper mapper) {
        super(mapper);
    }

    /**
     * 获取可发送的email列表，应符合以下条件的消息：
     *
     * <ul>
     *     <li>未发送状态，且发送时间小于当前时间的消息</li>
     *     <li>发送失败（发送失败说明已经发送过，不需要判断是否已到发送时间）且重试次数小于配置值的消息</li>
     * </ul>
     */
    public List<EmailMessage> listMessage4Send() {
        Example example = new Example(EmailMessage.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThanOrEqualTo("resendNum", 3);
        criteria.andEqualTo("status", SendStatusEnum.FAILURE.val);
        setCommonCriteria(criteria);

        Example.Criteria orCriteria = example.createCriteria();
        orCriteria.andEqualTo("status", SendStatusEnum.NOT_SEND.val);
        setCommonCriteria(orCriteria);

        example.or(orCriteria);

        return selectByExample(example, false);     //无需以租户为边界
    }

    private void setCommonCriteria(Example.Criteria criteria) {
        criteria.andLessThanOrEqualTo("sendDate", new DateTime().toDate());
    }
}
